#include <QApplication>
#include "homepage.h"
#include "detectionwindow.h"
#include "enrollwindow.h"
#include "loginwindow.h"
#include "notepadwindow.h"
#include <QSqlDatabase>


void connectDataBase()
{
    //添加数据库，连接数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("../Qtobject/data.db");
    db.open();
}

void InitializeLog()
{

    qDebug()<<2;
    QString str = qApp->applicationDirPath();
    str = QDir::currentPath();
    str += "/logDir";
    str = QDir::toNativeSeparators(str);//将“/”转换为“\\”
    //QString logDirPath = "E:/QQQt/1/ProjectLoginWindow/logDir";
    //QDir dir(logDirPath);

    //检查目录，如果不存在则创建
    QDir dir(str);
    if (!dir.exists())
    {
        dir.mkpath(str);
    }
    qDebug() << "Log directory path:" << str;

    //删除超过7天的文件
    QDateTime deleteDateTime = QDateTime::currentDateTime().addDays(-7);//获取七天前的日期时间
    QFileInfoList fileList = dir.entryInfoList();
    for (QFileInfo info : fileList)
    {
        if (info.fileName() == "." || info.fileName() == "..")   continue;
        int seconds = deleteDateTime.secsTo(info.created());//前7天的时间到文件的创建时间
        if (seconds < 0)
        {
            info.dir().remove(info.fileName());
        }
    }


}
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{

    // 加锁
        static QMutex mutex;
        mutex.lock();

        QByteArray localMsg = msg.toLocal8Bit();

        QString msgType("");
        switch (type)
        {
        case QtDebugMsg:
            msgType = QString("Debug");
            break;
        case QtWarningMsg:
            msgType = QString("Warning");
            break;
        case QtCriticalMsg:
            msgType = QString("Critical");
            break;
        case QtFatalMsg:
            msgType = QString("Fatal");
            break;
        }

        // 设置输出信息格式
        QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString strMessage = QString("[%1]-[flie:%2    line:%3    datetime:%4]--------------------- %5")
                .arg(msgType)					//消息类型
                .arg(context.file)				//消息所在文件
                .arg(context.line)				//消息所在行
                .arg(strDateTime)				//日期时间
                .arg(localMsg.constData());		//消息

        //获取文件路径
        QString str = qApp->applicationDirPath();
        //    str = str.left(str.lastIndexOf("/"));//获取上一级目录路径
        str = QDir::currentPath();
        str += "/logDir";

        QString filePath = QDate::currentDate().toString("yyyy-MM-dd");
        filePath += ".txt";
        filePath = str + "/" + filePath;
        filePath = QDir::toNativeSeparators(filePath);//将“/”转换为“\\”

        // 输出信息至文件中（读写、追加形式）
        QFile file(filePath);
        file.open(QIODevice::ReadWrite | QIODevice::Append);
        QTextStream stream(&file);
        stream << strMessage << "\r\n";
        file.flush();
        file.close();

        // 解锁
        mutex.unlock();
}


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    connectDataBase();
    InitializeLog();						//初始化
    qInstallMessageHandler(myMessageOutput);//自定义日志输出
  //#endif
    // 测试日志输出
    qDebug() << "This is a debug message.";
    qInfo() << "This is an info message.";
    qWarning() << "This is a warning message.";
    qCritical() << "This is a critical message.";
   // qDebug("This is a debug test message.");

    //HomePage w;
   // DetectionWindow d;
    LoginWindow w;
    w.show();
    //d.show();

    return a.exec();
}
